package cis.android.signlocker.datatool;

import android.content.Context;
import android.os.AsyncTask;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import cis.android.signlocker.data.XmlSignData;
import cis.android.signlocker.signableview.SignDataRow;

/**
 * Created by MaiHoàng on 19/03/2014.
 */
public class DataSender {
    private List<OnFinishListener> onFinishListener;

    public DataSender() {
        onFinishListener = new ArrayList<OnFinishListener>();
    }

    /**
     * Set sự kiện gửi xong
     * @param listener
     */
    public void setOnFinishListener(OnFinishListener listener) {
        onFinishListener.add(listener);
    }

    /**
     * Gửi dữ liệu
     * @param signData
     * @param ip
     * @param port
     */
    public void sendSignData(ArrayList<SignDataRow> signData, String ip, int port) {
        AsyncSender sender = new AsyncSender(ip, port);
        sender.execute(signData);
    }

    interface OnFinishListener {
        public void onSuccess();

        public void onError(Exception e);
    }

    class AsyncSender extends AsyncTask<ArrayList<SignDataRow>, Integer, Void> {

        private String ip;
        private int port;

        AsyncSender(String ip, int port) {
            this.ip = ip;
            this.port = port;
        }

        @Override
        protected Void doInBackground(ArrayList<SignDataRow>... arrayLists) {
            try {
                Socket cl = new Socket(ip, port);
                PrintWriter pw = new PrintWriter(cl.getOutputStream(), true);

                String XmlData = XmlSignData.SignDataToXml(arrayLists[0]);
                pw.println(XmlData);
                cl.close();

                for (OnFinishListener listener : onFinishListener) {
                    listener.onSuccess();
                }
            }
            catch (Exception e) {
                for (OnFinishListener listener : onFinishListener) {
                    listener.onError(e);
                }
            }

            return null;
        }
    }
}
